package com.wutoon.etl.service.impl;

import com.alibaba.fastjson.JSON;
import com.wutoon.etl.constant.CommonConstant;
import com.wutoon.etl.handler.HttpCollectHandler;
import com.wutoon.etl.mapper.BizOperateRecordManage;
import com.wutoon.etl.mapper.DataSourceManage;
import com.wutoon.etl.pojo.DataSourceDO;
import com.wutoon.etl.pojo.Http2DbTask;
import com.wutoon.etl.pojo.MapReduceShard;
import com.wutoon.etl.pojo.PowerJobResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.sql.*;

/**
 * @author 武兴云/72176468
 * @version 1.0
 * @date 2023/11/13 4:23 PM
 * @description 运维服务
 */
@Service
@Slf4j
public class DataCollectService {

    @Resource
    private DataSourceManage dataSourceManage;

    @Resource(name = "outRestTemplate")
    private RestTemplate outRestTemplate;

    @Resource
    private BizOperateRecordManage bizOperateRecordManage;

    public PowerJobResult<?> collectData(MapReduceShard shard) {
        log.info("DataCollectService collectData start, param:{}", JSON.toJSONString(shard));
        try {
            Http2DbTask task = JSON.parseObject(shard.getCustomParam().toJSONString(), Http2DbTask.class);
            // 校验参数
            if (task.getIncrease() == null || StringUtils.isEmpty(task.getTargetTable()) ||
                    StringUtils.isEmpty(task.getTargetSql()) || StringUtils.isEmpty(task.getTargetCode())
                    || task.getCollectSource() == null) {
                return new PowerJobResult<>(false, "非法参数, 必填参数为空");
            }
            DataSourceDO targetDataSource = dataSourceManage.queryByCode(task.getTargetCode());
            task.setTargetSource(targetDataSource);

            HttpCollectHandler handler = new HttpCollectHandler(task, outRestTemplate, bizOperateRecordManage);
            handler.start();
            log.info("DataCollectService collectData end");
            return new PowerJobResult<>(true, shard);
        } catch (Exception e) {
            log.error("DataCollectService collectData error:", e);
            return new PowerJobResult<>(false, e.getMessage());
        }
    }
    public Connection connect(DataSourceDO dataSourceDO) {
        try {
            Class.forName(dataSourceDO.getDriver());
            DriverManager.setLoginTimeout(CommonConstant.TIMEOUT_SECONDS);
            return DriverManager.getConnection(dataSourceDO.getJdbcUrl(), dataSourceDO.getUsername(), dataSourceDO.getPassword());
        } catch (Exception e) {
            throw new RuntimeException("initialize datasource connection error");
        }
    }
}
